package com.demomaster.quickaccessibility.service;

import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;

import android.Manifest;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;

import java.util.HashMap;
import java.util.Map;

public class QuickAccessibilityService extends BaseAccessibilityService {
    public static final String TAG = QuickAccessibilityService.class.getSimpleName();
    public static QuickAccessibilityService instance;
    public static final int QuickAccessibilityService_Event = 1035445;//无障碍服务事件标识
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        handler = new Handler();
        QuickAccessibility.getInstance().onServiceCreate(instance);
    }

    public AccessibilityWindowInfo getWindowById(int id) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            for (AccessibilityWindowInfo windowInfo : getWindows()) {
                if (windowInfo.getId() == id) {
                    return windowInfo;
                }
            }
        }
        return null;
    }

    //实现辅助功能
    @Override
    public void onAccessibilityEvent(android.view.accessibility.AccessibilityEvent event) {
        super.onAccessibilityEvent(event);
        int eventType = event.getEventType();
        //QDLogger.println("onAccessibilityEvent:" + eventType);
        switch (eventType) {
            case android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                Log.d(TAG,"窗口信息，当前包名:" + getCurrentPackageName() + ",页面:" + getCurrentActivityName());
                AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
                if (accessibilityNodeInfo != null) {
                    Log.d(TAG,"TYPE_WINDOW_STATE_CHANGED_0:" + event.getWindowId() + "]" + event.getPackageName() + "<===>" + event.getClassName() + ",root=" + accessibilityNodeInfo.getWindowId() + "]" + accessibilityNodeInfo.getPackageName() + ",act=" + accessibilityNodeInfo.getClassName());
                    if (!TextUtils.isEmpty(event.getPackageName())&&event.getPackageName().equals(accessibilityNodeInfo.getPackageName())) {
                        setLatestComponent(accessibilityNodeInfo.getPackageName(), event.getClassName());
                    }
                } else {
                    setLatestComponent(event.getPackageName(), event.getClassName());
                    Log.d(TAG,"TYPE_WINDOW_STATE_CHANGED_3:" + event.getWindowId() + "]" + event.getPackageName() + "<===>" + event.getClassName());
                }
                //AccessibilityWindowInfo windowInfo = getWindowById(event.getWindowId());
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    if (windowInfo != null && windowInfo.isFocused()) {
//                        setLatestComponent(accessibilityNodeInfo.getPackageName(), event.getClassName());
//                    }
//                }
                //                String className1 = event.getClassName().toString();
                //                String packageName1 = event.getPackageName().toString();
                //
                //                //监听当前窗口变化，获取Package名和Class名
                //                Log.i(TAG,"shine:onAccessibilityEvent,className =" + className1 );
                //                Log.i(TAG,"shine:onAccessibilityEvent,packageName=" + packageName1 );
//                AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
//                currentPackageName = accessibilityNodeInfo == null ? "" : (accessibilityNodeInfo.getPackageName() + "");
//                String className = event.getClassName() == null ? null : event.getClassName().toString();
//                if (!TextUtils.isEmpty(currentPackageName) && !TextUtils.isEmpty(className)) {
//                    ansyActivity(className);
//                    Log.d(TAG,"窗口更新，当前包名:" + getCurrentPackageName() + ",页面:" + currentActivityName);
//                }
                break;
            default:
                break;
        }

        if (eventType == TYPE_WINDOW_CONTENT_CHANGED) {
            long t1 = System.currentTimeMillis() - lastTime;
            if (t1 < 3000) {
                delayEvent = new QuickAccessibilityEvent(event);
                handler.removeCallbacks(delayRunnable);
                handler.postDelayed(delayRunnable, 3000);
                return;
            }else {
                lastTime = System.currentTimeMillis();
            }
        }

        AccessNodeFinder.getInstance().noteUpdate();
        QuickAccessibility.getInstance().onAccessibilityEvent(new QuickAccessibilityEvent(event));
        //AccessibilityHelper.onAccessibilityEvent(this, event);
        /*
        switch (eventType) {
            case AccessibilityEvent.TYPE_VIEW_CLICKED:
                Log.i(TAG, "捕获到点击事件");
                AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
                if (nodeInfo != null) {
                    // 查找text为Test!的控件
                    List<AccessibilityNodeInfo> button = nodeInfo.findAccessibilityNodeInfosByText("Test!");
                    nodeInfo.recycle();
                    for (AccessibilityNodeInfo item : button) {
                        Log.i(TAG, "long-click button!");
                        // 执行长按操作
                        item.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
                        item.getParent().performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
                    }
                }
                break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                //Log.e(TAG, "窗口切换" + event.getClassName());
                break;
            case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED:
                //Log.e(TAG, "文字改变" + event.getClassName());
                break;
        }*/
        //  }
    }

    /**
     * 模拟全局按键 performGlobalAction "Android 4.1及以上系统才支持此功能
     */
    @Override
    public void onInterrupt() {
        Log.d(TAG,"辅助功能被迫中断");
    }

    @Override
    public void onDestroy() {
        QuickAccessibility.getInstance().onServiceDestroy();
        instance = null;
        super.onDestroy();
        Log.i(TAG, "辅助功能已关闭");
    }

    //跳转系统自带界面 辅助功能界面
    public static void startSettintActivity(Context context) {
        /*Intent intent = new Intent(context, DialogWindowActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("permission", Manifest.permission.BIND_ACCESSIBILITY_SERVICE);
        intent.putExtras(bundle);
        (context).startActivity(intent);*/
        //TODO QuickPermission.with().permissions(Manifest.permission.BIND_ACCESSIBILITY_SERVICE).request();
    }

}
